﻿using System;//
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using Citi.SecurityHelper;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using WindowsInput;
using Citi.SecurityWebBrowser;
using System.Timers;
using System.IO;
using System.Diagnostics;


namespace Citi.Encryption
{
    public partial class Form2 : Form
    {
        //CitiWebBrowser browser;
        static string LogPath { get; set; }
        SHDocVw.WebBrowser_V1 axbrowser;
        string reportName;
        private const string JavascriptFrameBody = "window.frames['headerPlusFrame'].frames['dataFrame'].frames['workspaceFrame'].frames['workspaceBodyFrame']";

        public Form2()
        {
            InitializeComponent();
        }

        private void Form2_Load(object sender, EventArgs e)
        {
            //using (var client = new PearlBO.SessionPortClient())
            //{
            //    var oCon = new Connection("http://boserver:port/dswsbobje/services/session");
            //    Session m_session = new Session(oCon);

            //    EnterpriseCredential oEnterpriseCredential = new EnterpriseCredential();
            //    oEnterpriseCredential.Login = "John";
            //    oEnterpriseCredential.Password = "MyPassword1973";
            //    oEnterpriseCredential.Locale = "en_US";
            //    oEnterpriseCredential.TimeZone = "GMT+01:00";

            //    SessionInfo oSessionInfo = m_session.Login(oEnterpriseCredential);
            //}

            //using (var client = new PearlBO.SessionPortClient())
            //{
            //    var credential = new PearlBO.EnterpriseCredential
            //    {
            //        Login = "FC16291",
            //        Password = "Dexter010",
            //        Domain = "lac",
            //        Domain = "plboprg.wlb2.nam.nsroot.net:14620",
            //        AuthType = "SSO"
            //    };
            //    var session = client.getServerInfo();


            //    client.login(null, client.getVersion());
            //}

            //return;

            //browser = new CitiWebBrowser();

            var hrUrl = ("https://hronline.brazil.citigroup.net/siteminderagent/forms/login.fcc");
            var p2pUrl = "https://signon.p2p.citigroup.net/";
            var i7UatUrl = "https://uat.brazilweb.br.citicorp.com/siteminderagent/forms/login.fcc?TYPE=33554433&REALMOID=06-3f395aef-bd9c-0006-0000-534600005346&GUID=&SMAUTHREASON=0&METHOD=GET&SMAGENTNAME=-SM-d2MymqAkcJRTP8thRFmJWpl41jCQfYTR%2fi8pnlogZGruwMl8S1FUuyGVwJyyNylejod1uUPjavbLoz1HKPzHs2NfAVcAVjKZ&TARGET=-SM-%2fAPPSL%2fi7%2fconfiguracao%2easpx%2fsistema";
            var gdwUrl = "https://gdw-wfr.nam.nsroot.net/wfrbo/AnalyticalReporting/WebiView.do?bypassLatestInstance=true&cafWebSesInit=true&appKind=InfoView&service=/InfoViewApp/common/appService.do&loc=en&pvl=en_US&ctx=standalone&actId=468&objIds=921989&containerId=28146&pref=maxOpageU%3D50%3BmaxOpageUt%3D200%3BmaxOpageC%3D10%3Btz%3DAmerica%2FNew_York%3BmUnit%3Dinch%3BshowFilters%3Dtrue%3BsmtpFrom%3Dtrue%3BpromptForUnsavedData%3Dtrue%3B";
            var pearlUrl = "https://pearl.nj.ssmb.com/siteminderagent/forms/login.fcc?TYPE=33554433&REALMOID=06-fb51622c-add9-1001-9bdc-847a5366ff21&GUID=&SMAUTHREASON=0&METHOD=GET&SMAGENTNAME=-SM-TSXzCZBCWQfzzR6LEV6XtEMrota02ItSl0QgFPxXin03Wt9NJusCYSasBcT6zdoJT%2fuU6B%2b%2b02sSh2OVblMd8gXfnNQ9TyP9&TARGET=-SM-%2fpsp%2fplpfprg%2fEMPLOYEE%2fEPM%2fc%2fBCC_REPORTS_HOME%2eBCC_BO_R3_LINK%2eGBL%3fFolderPath%3dPORTAL_ROOT_OBJECT%2eBCC_COUNTRY_CORE%2eBCC_REPORTING%2eBCC_BO_R3_LINK_GBL%26IsFolder%3dfalse%26IgnoreParamTempl%3dFolderPath-%2cIsFolder";
            reportName = "PEARL_REPORT_Total_2014_With_Dolar constant_FT : 11794969";
            var url = pearlUrl;
            //url = "https://pearl.nj.ssmb.com/psp/plpfprg/EMPLOYEE/EPM/s/WEBLIB_PTPP_SC.HOMEPAGE.FieldFormula.IScript_AppHP?pt_fname=BCC_COUNTRY_CORE&FolderPath=PORTAL_ROOT_OBJECT.BCC_COUNTRY_CORE&IsFolder=true";
            //url = "https://pearl.nj.ssmb.com/psc/plpfprg/EMPLOYEE/EPM/s/WEBLIB_PTPP_SC.HOMEPAGE.FieldFormula.IScript_AppHP?scname=BCC_COUNTRY_CORE&secondary=true&fname=BCC_REPORTING&pt_fname=BCC_REPORTING&PortalCacheContent=true&PSCache-Control=role%2cmax-age%3d60&FolderPath=PORTAL_ROOT_OBJECT.BCC_COUNTRY_CORE.BCC_REPORTING&IsFolder=true";
            //url = "http://plboprg.wlb2.nam.nsroot.net:14620/bobjpsenterprise/jsp/ContextualAwareness/initURE.jsp?infoview=http://plboprg.wlb2.nam.nsroot.net:14620/PartnerPlatformService/service/app/logon.object&vendor=PeopleSoft&cms=corpbo126p.nam.nsroot.net:14670&auth=secpsenterprise&domain=PLPFPRG&token=AAAAqAECAwQAAQAAAAACvAAAAAAAAAAsAARTaGRyAgBOdQgAOAAuADEAMBRI5t1/PBZ6D7YofAnzOlcW4F2AdwAAAGgABVNkYXRhXHicHYtLDkBAEAVrEEsr1yCGFqx9ZiMycQGncDuH8+ikqpN+r4HbJWmGQ5M8nwt2FgxPJ6aclYNQMhO4iEojmzgJRkujklFpd7IefvfUwmTPKA/KTZev9QK0pQwb";
            //browser.LogSingleSignOn("ND61955", SecurityHelper.LoginType.Sso, "https://procure2pay.citigroup.net/");
            //PTS
            url = "https://itboprg.nam.nsroot.net/InfoViewApp/logon.jsp";
            axbrowser = (SHDocVw.WebBrowser_V1)browser.ActiveXInstance;
            axbrowser.NewWindow += new SHDocVw.DWebBrowserEvents_NewWindowEventHandler(Web_V1_NewWindow);
            browser.Navigated += browser_Navigated;
            browser.LogSingleSignOn("ND61955", SecurityHelper.LoginType.Sso, url);
            //browser.LogSingleSignOn("ND61955", SecurityHelper.LoginType.Sso, url);
            //browser.Navigate(url);

            //var processes = Process.GetProcessesByName("iexplore");

            //var dialog = processes.FirstOrDefault(x => x.MainWindowTitle.EndsWith("Completed"));

            //if (dialog == null) return;

            //IntPtr child = FindWindowEx(dialog.MainWindowHandle, default(IntPtr), null, null);
            //SendMessage(child, 0x0102, KeyS, 1);
            // SendMessage(child, 0x000C, 0, "s");
            
            //browser.Navigate("https://download.mozilla.org/?product=firefox-30.0-SSL&os=osx&lang=pt-BR");
            ////browser.FileDownload += new EventHandler(browser_FileDownload);
            //timerDialogDownloadFile.Elapsed += timerDialogDownloadFile_Elapsed;
            //timerDialogDownloadFile.Start();
        }

        void browser_FileDownload(object sender, EventArgs e)
        {
            browser.AllowNavigation = false;
        }
        System.Timers.Timer timerDialogDownloadFile = new System.Timers.Timer(5000);

        private void timerDialogDownloadFile_Elapsed(object sender, ElapsedEventArgs e)
        {
            BeginInvoke(new timerPointer(SaveDownload));
        }

        private void SaveDownload()
        {
            ////var processes = Process.GetProcessesByName("iexplore");
            ////var processes = Process.GetProcessesByName(Process.GetCurrentProcess().ProcessName);

            ////var dialog = processes.FirstOrDefault(x => x.MainWindowTitle.EndsWith("Completed"));
            ////var dialog = processes.FirstOrDefault(x => string.IsNullOrWhiteSpace( x.MainWindowTitle) && x.MainWindowTitle != Text);
            //var dialog = Process.GetCurrentProcess();
            ////var active = GetActiveWindow();
            //var fore = GetForegroundWindow();
            ////return;
            ////  if (dialog != null) return;

            timerDialogDownloadFile.Stop();

            //var handle = GetActiveWindow2();
            //// IntPtr child = FindWindowEx(dialog.MainWindowHandle, default(IntPtr), null, null);
            //IntPtr child = FindWindowEx((IntPtr)handle, dialog.MainWindowHandle, null, null);
            ////IntPtr child2 = FindWindowEx(fore, default(IntPtr), null, null);

            ////var ss = GetActiveWindow();
            ////var sdsds = GetLastActivePopup(Handle);
            //var dialogHandle = GetLastActivePopup(dialog.MainWindowHandle);
            //File.AppendAllLines(@"c:\temp\handles.txt", new string[1] { dialogHandle.ToString() });
            //var buttonTitle = "&Save";
            ////var dialogButtonHandle = FindWindowEx(child, IntPtr.Zero, "Button", buttonTitle);
            //var dialogButtonHandle = FindWindowEx(dialogHandle, IntPtr.Zero, "Button", buttonTitle);
            //File.AppendAllLines(@"c:\temp\handles.txt", new string[1] { dialogButtonHandle.ToString() });

            //var teste = FindWindow(null, "File Download");
            //File.AppendAllLines(@"c:\temp\handles.txt", new string[1] { teste.ToString() });
            //SetForegroundWindow(teste);

            //for (int i = 0; i < 100; i++)
            //{
            //    Application.DoEvents();
            //    Thread.Sleep(100);
            //}
            //dialogButtonHandle = FindWindowEx(teste, IntPtr.Zero, "Button", buttonTitle);
            //File.AppendAllLines(@"c:\temp\handles.txt", new string[1] { dialogButtonHandle.ToString() });

            //const int WM_LBUTTONDOWN = 0x0201;
            //const int WM_LBUTTONUP = 0x0202;
            //const int BM_SETSTATE = 0x00F3;

            //SendMessage(dialogButtonHandle, WM_LBUTTONDOWN, 0, IntPtr.Zero);   //send left button mouse down
            //SendMessage(dialogButtonHandle, WM_LBUTTONUP, 0, IntPtr.Zero);     //send left button mouse up
            //SendMessage(dialogButtonHandle, BM_SETSTATE, 1, IntPtr.Zero);     //send 

            ////res = SendMessage(hWndBtn, TCM_SETCURFOCUS, 1, ByVal 0&)
            //// res = PostMessage(hWndBtn, BM_CLICK, ByVal 0&, ByVal 0&)
            //// res = SendMessage(hWndBtn, WM_COMMAND, 0&, 0&)

            ////const int BM_CLICK = 0x00F5;
            ////SendMessage(dialogButtonHandle, BM_CLICK, new IntPtr(0), new IntPtr(0));

            ////callBackPtr = new CallBackPtr(Report);
            ////EnumWindows(callBackPtr, 0);
            ////SendMessage(dialogButtonHandle, WM_COMMAND, (BN_CLICKED << 16) | IDOK, dialogButtonHandle );
            ////SendMessage(child, 0x0102, KeyS, 1);
            ////SendMessage(dialogHandle, 0x0102, KeyS, 1);
            ////SendMessage(dialogButtonHandle, BM_CLICK, 1, 0);
            ////SendMessage(child, 0x000C, 0, "s");


            // Download();

        }

        int ButtonId = 4427;
        void Download()
        {
            const string cClsName = "#32770";
            var aWinText = new string[]{
                //"File Download - Security Warning",
                "File Download",
                "File Download - Security Warning",
                "Save As",
                "Download complete"
            };

            //for (i = 0; (i <= 2); i++)
            var hWndUI = default(IntPtr);
            while (hWndUI == IntPtr.Zero)
            {
                Sleep(100);
                hWndUI = FindWindow(cClsName, aWinText[0]);
            }

            for (int i = 0; i < 100; i++)
            {
                Application.DoEvents();
                SetForegroundWindow(hWndUI);
                //LockSetForegroundWindow(hWndUI);
                Sleep(200);
            }
            
            var hWndBtn = FindWindowEx(hWndUI, IntPtr.Zero, "Button", "&Save");
            Sleep(200);

            IntPtr hWndButton = GetDlgItem(hWndUI, ButtonId);
            int wParam = (BN_CLICKED << 16) | (ButtonId & 0xffff);
            SendMessage(hWndUI, WM_COMMAND, wParam, hWndBtn);
            

            //SendMessage(hWndBtn, (uint)WM.WM_KEYDOWN, (int)VK.VK_LEFT, IntPtr.Zero);
            //SendMessage(hWndBtn, (uint)WM.WM_KEYUP, (int)VK.VK_LEFT, IntPtr.Zero);
            //SendMessage(hWndBtn, (uint)WM.WM_KEYDOWN, (int)VK.VK_LEFT, IntPtr.Zero);
            //SendMessage(hWndBtn, (uint)WM.WM_KEYUP, (int)VK.VK_LEFT, IntPtr.Zero);
            //SendMessage(hWndBtn, (uint)WM.WM_KEYDOWN, (int)VK.VK_LEFT, IntPtr.Zero);
            //SendMessage(hWndBtn, (uint)WM.WM_KEYUP, (int)VK.VK_LEFT, IntPtr.Zero);
            //SendMessage(hWndUI, 0x0102, KeyS, 1);
            //SendMessage(hWndBtn, 0x0102, KeyS, 1);
            //SendMessage(hWndUI, 0x000C, 0, "s");
            //SendMessage(hWndBtn, 0x000C, 0, "s");
            return;
            ////IntPtr ip = new IntPtr(0x0D); //ENTER
            ////const int WM_BUTTONDOWN = 0x0100;
            ////const int WM_BUTTONUP = 0x0101;

            ////SendMessage(hWndUI, WM_BUTTONDOWN, ip, IntPtr.Zero);
            ////SendMessage(hWndUI, WM_BUTTONUP, ip, IntPtr.Zero);

            //SendMessage(hWndBtn, TCM_SETCURFOCUS, (IntPtr) 1, IntPtr.Zero);
            //SendMessage(hWndBtn, BM_CLICK, (IntPtr)1, IntPtr.Zero);
            ////PostMessage(hWndBtn, BM_CLICK, IntPtr.Zero, IntPtr.Zero);
            //SendMessage(hWndBtn, WM_COMMAND, IntPtr.Zero, IntPtr.Zero);
            //  3, wait until Download complete appears
            hWndUI = default(IntPtr);

            //  increase timeOut with bigger files
            while (hWndUI == IntPtr.Zero)
            {
                hWndUI = FindWindow(cClsName, aWinText[2]);
                //  optional open folder
                hWndBtn = FindWindowEx(hWndUI, IntPtr.Zero, "Button", "Open &Folder");
                SendMessage(hWndBtn, TCM_SETCURFOCUS, 1, IntPtr.Zero);
                PostMessage(hWndBtn, BM_CLICK, IntPtr.Zero, IntPtr.Zero);
                //SendMessage(hWndBtn, BM_CLICK, ByVal 0&, ByVal 0&)
                SendMessage(hWndBtn, WM_COMMAND, IntPtr.Zero, IntPtr.Zero);
                Application.DoEvents();
            }
        }
        [DllImport("user32.dll", SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        static extern bool LockSetForegroundWindow(IntPtr uLockCode);
        const int WM_COMMAND = 0x0111;
        const int BN_CLICKED = 0;

        [DllImport("user32.dll")]
        static extern IntPtr GetDlgItem(IntPtr hWnd, int nIDDlgItem);

        [DllImport("user32.dll")]
        static extern IntPtr SendMessage(IntPtr hWnd, int Msg, int wParam, IntPtr lParam);

        public enum VK : int
        {
            VK_DOWN = 0x28,
            VK_UP = 0x26,
            VK_LEFT = 0x25,
            VK_RIGHT = 0x27
        }

        public enum WM
        {
            WM_KEYUP = 0x0101,
            WM_KEYDOWN = 0x0100,
            WM_ENTER = 0x0D
        }

        public const uint TCM_SETCURFOCUS = 0x1330;
        public const uint BM_CLICK = 0xf5;
        //private const uint WM_COMMAND = 0x111;

        //[DllImport("user32.dll", EntryPoint = "FindWindowA")]
        //public static extern long FindWindow(string lpClassName, string lpWindowName);

        [DllImport("user32.dll", SetLastError = true)]
        static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);

        //[DllImport("user32.dll", EntryPoint = "SendMessageA")]
        //public static extern long SendMessage(long hWnd, long wMsg, long wParam, int lParam);

        //[DllImport("user32.dll", EntryPoint = "PostMessageA")]
        //public static extern long PostMessage(long hWnd, long wMsg, long wParam, long lParam);

        [return: MarshalAs(UnmanagedType.Bool)]
        [DllImport("user32.dll", SetLastError = true)]
        static extern bool PostMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);

        //[DllImport("user32.dll")]
        //public static extern long SetForegroundWindow(long hWnd);

        [DllImport("kernel32.dll")]
        static extern void Sleep(uint dwMilliseconds);

        [DllImport("user32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        static extern bool SetForegroundWindow(IntPtr hWnd);
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, IntPtr lParam);
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        public static extern int SendMessage(IntPtr hWnd, uint msg, int wParam, IntPtr lParam);


        public delegate bool CallBackPtr(int hwnd, int lParam);
        private CallBackPtr callBackPtr;

        [DllImport("user32.dll")]
        private static extern int EnumWindows(CallBackPtr callPtr, int lPar);

        public static bool Report(int hwnd, int lParam)
        {
            var stringBuilder = new StringBuilder(256);
            var title = GetWindowText(hwnd, stringBuilder, stringBuilder.Capacity);
            File.AppendAllLines(@"c:\temp\handles.txt", new List<string> { hwnd.ToString() + " - " + title });
            return true;
        }

        [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
        internal static extern int GetWindowText(IntPtr hWnd, [Out] StringBuilder lpString, int nMaxCount);
        //[DllImport("user32.dll", SetLastError = true)]
        //internal static extern long FindWindow(string lpClassName, string lpWindowName);
        [DllImport("user32.dll", SetLastError = true)]
        static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

        private int GetActiveWindow2()
        {

            const int nChars = 256;
            int handle = 0;
            StringBuilder Buff = new StringBuilder(nChars);

            handle = GetForegroundWindow();

            if (GetWindowText(handle, Buff, nChars) > 0)
            {
                return handle;
                //MessageBox.Show(Buff.ToString() + handle.ToString());
                //this.captionWindowLabel.Text = Buff.ToString();
                //this.IDWindowLabel.Text = handle.ToString();
            }
            return 0;
        }

        const int KeyS = 0x53;
        //const int BM_CLICK = 0x00F5;

        [DllImport("user32.dll")]
        static extern int GetForegroundWindow();

        [DllImport("user32.dll")]
        static extern int GetWindowText(int hWnd, StringBuilder text, int count);

        //[DllImport("user32.dll", EntryPoint = "FindWindowEx")]
        //public static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);
        [DllImport("User32.dll")]
        public static extern int SendMessage(IntPtr hWnd, int uMsg, int wParam, string lParam);
        [DllImport("user32.dll", EntryPoint = "SendMessage", SetLastError = true, CharSet = CharSet.Auto)]
        private static extern int SendMessage(IntPtr hwnd, uint wMsg, int wParam, int lParam);
        [DllImport("user32.dll")]
        static extern IntPtr GetActiveWindow();
        [DllImport("user32.dll")]
        static extern IntPtr GetLastActivePopup(IntPtr hWnd);


        void browser_Navigated(object sender, WebBrowserNavigatedEventArgs e)
        {
            if (!e.Url.OriginalString.Contains("appKind=InfoView&service=%2FInfoViewApp%2Fcommon%2FappService.do"))
                return;

            browser.DocumentCompleted += InboxDocumentCompleted;
        }

        private void Web_V1_NewWindow(string URL, int Flags, string TargetFrameName, ref object PostData, string Headers, ref bool Processed)
        {
            Processed = true;
            browser.Navigate(URL);
        }

        int documentStep = 0;

        private void InboxDocumentCompleted(object sender, EventArgs e)
        {
            var frame = GetWorkspaceBodyFrame();

            if (frame == null) return;

            var tableReports = frame.Document.GetElementById("ListingURE_listMainTable");

            if (tableReports == null) return;

            var tbody = tableReports.Children.Cast<HtmlElement>().FirstOrDefault(x => x.TagName.ToUpper() == "TBODY");

            if (tbody == null) return;

            documentStep++;
            if (documentStep < 6) return;

            browser.DocumentCompleted -= InboxDocumentCompleted;
            Log(string.Format("Looking for report '{0}'", reportName));

            var report = GetReports(tbody.Children.Cast<HtmlElement>().ToList(), reportName);

            if (report != null)
            {
                var myHidden = tableReports.Document.GetElementById(string.Format("ListingURE_doubleClickAction{0}", report.Index));
                ReportRefreshLoadCompleted(myHidden);
            }
            else
            {
                Log(string.Format("#Error No report was found named '{0}'", reportName));
                Environment.Exit(Environment.ExitCode);
            }


        }

        string lastRefreshData;
        static readonly string JavascriptRefreshDate = string.Format("{0}.frames['webiViewFrame'].document.getElementById('statusRefDate').innerHTML", JavascriptFrameBody);
        private System.Timers.Timer timerParametersWindow = new System.Timers.Timer { Interval = 2000 };

        private void ReportRefreshLoadCompleted(HtmlElement myHidden)
        {
            Log("Opening report");

            var val = myHidden.GetAttribute("value");
            val = val.Substring("javascript:".Length);
            val = val.Replace("cafAction", "invokeAction");

            var frame = GetWorkspaceBodyFrame();
            frame.Document.InvokeScript("eval", new string[] { val });

            browser.DocumentCompleted += OpenReportCompleted;


        }

        void OpenReportCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            browser.DocumentCompleted -= OpenReportCompleted;

            startParametersWindows = DateTime.Now;
            timerParametersWindow.Elapsed += timerParametersWindow_Elapsed;
            timerParametersWindow.Start();

            browser.DocumentCompleted += RefreshDataCompleted;
        }

        int count = 0;
        void RefreshDataCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            if (count < 9)
            {
                count++;
                return;
            }
            browser.DocumentCompleted -= RefreshDataCompleted;

            //var refreshDateFound = false;

            //while (!refreshDateFound)
            //    refreshDateFound = 
            browser.WaitUntilExist(JavascriptRefreshDate, 2000);

            lastRefreshData = (String)browser.Document.InvokeScript("eval", new[] { JavascriptRefreshDate });
            //DownloadReport();

            timerDownloadFile = new System.Timers.Timer(2000);
            timerDownloadFile.Elapsed += timerDownloadFile_Elapsed;
            timerDownloadFile.Start();
        }

        System.Timers.Timer timerDownloadFile;

        private void timerDownloadFile_Elapsed(object sender, ElapsedEventArgs e)
        {
            BeginInvoke(new timerPointer(DownloadReport));
        }

        private void DownloadReport()
        {
            var currentRefreshData = (String)browser.Document.InvokeScript("eval", new[] { JavascriptRefreshDate });

            Log("Business Objects is refreshing the report");
            if (lastRefreshData == currentRefreshData) return;
            //while (lastRefreshData == currentRefreshData)
            //{
            //    Application.DoEvents();
            //    Thread.Sleep(500);

            //    //if (browser.CanEvalScript)
            //    currentRefreshData = (String)browser.Document.InvokeScript("eval", new[] { JavascriptRefreshDate });
            //}

            timerDownloadFile.Stop();
            Log("Business Objects has been refreshed the report");

            var javascriptLocation = string.Format("{0}.frames['webiViewFrame']", JavascriptFrameBody);
            var javascriptElement = string.Format("{0}.frames['webiViewFrame'].document.getElementById('{1}')", JavascriptFrameBody, "{0}");

            Log("Clicking on 'Document' button");
            browser.WaitUntilExist(string.Format(javascriptElement, "IconImg_Txt_iconMenu_icon_docMenu"));
            ClickOnElement("IconImg_Txt_iconMenu_icon_docMenu", javascriptLocation);

            Log("Clicking on 'Save as in Computer' button");
            browser.WaitUntilExist(string.Format(javascriptElement, "iconMenu_menu_docMenu_span_text_saveDocComputerAs"));
            ClickOnElement("iconMenu_menu_docMenu_span_text_saveDocComputerAs", javascriptLocation);

            Log("Clicking on 'Excel' button");
            browser.WaitUntilExist(string.Format(javascriptElement, "saveDocComputerMenu_span_text_saveXLS"));
            ClickOnElement("saveDocComputerMenu_span_text_saveXLS", javascriptLocation);

            Log("Download will start soon");
            UpdateFormTitle("Download will start soon");

            //browser.Navigating += webBrowser_Navigating;
            //browser.FileDownload += new EventHandler(browser_FileDownload);
            //browser.FileDownload+=new EventHandler(browser_FileDownload);
            axbrowser.DownloadBegin += new SHDocVw.DWebBrowserEvents_DownloadBeginEventHandler(axbrowser_DownloadBegin);
            axbrowser.DownloadComplete += new SHDocVw.DWebBrowserEvents_DownloadCompleteEventHandler(axbrowser_DownloadComplete);
        }

        void axbrowser_DownloadComplete()
        {
            //throw new NotImplementedException();
        }

        void axbrowser_DownloadBegin()
        {

        }

        int countStartDownload = 0;
        void browser_FileDownload(object sender, object e)
        {
            if (countStartDownload == 0)
            {
                countStartDownload++;
                return;
            }


            //new SHDocVw.WebBrowser().DownloadBegin += new SHDocVw.DWebBrowserEvents2_DownloadBeginEventHandler(BoExtraction_DownloadBegin);
        }

        //[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = false)]
        //static extern IntPtr SendMessage(IntPtr hWnd, Int32 Msg, IntPtr wParam, IntPtr lParam);

        //[DllImport("user32.dll", SetLastError = true)]
        //public static extern uint SendInput(uint nInputs, User32.Input[] pInputs, int cbSize);





        private void webBrowser_Navigating(object sender, WebBrowserNavigatingEventArgs e)
        {
            //e.Cancel = true;
            //var client = new WebClient();

            //client.DownloadDataCompleted += client_DownloadDataCompleted;
            //client.DownloadDataAsync(e.Url);
        }

        private bool ClickOnElement(string elementToClickId, string locationElement, WebBrowserDocumentCompletedEventHandler eventRemove = null, WebBrowserDocumentCompletedEventHandler eventAdd = null)
        {
            var javascriptClick = string.Format("{0}.document.getElementById('{1}')", locationElement, elementToClickId);

            if (!browser.AllElementExist(javascriptClick)) return false;

            if (eventRemove != null)
                browser.DocumentCompleted -= eventRemove;

            if (eventAdd != null)
                browser.DocumentCompleted += eventAdd;

            browser.Document.InvokeScript("eval", new[] { string.Format("{0}.click();", javascriptClick) });
            return true;
        }

        private void UpdateFormTitle(string message)
        {
            Text = string.Format("{0} - {1}", browser.Document.Title, message);
        }

        static void Log(string message)
        {
            if (LogPath == null) return;
            File.AppendAllLines(LogPath, new[] { message });
        }

        private Report GetReports(IList<HtmlElement> trs, string reportName)
        {
            var reports = new List<Report>();

            foreach (var tr in trs)
            {
                try
                {
                    reports.Add(new Report
                    {
                        ElementClick = tr.Children[0],
                        //Title = tr.Children[2].Children[0].InnerText
                        Title = tr.Children[6].Children[0].GetElementsByTagName("a")[0].GetAttribute("title"),
                        Index = tr.Children[0].FirstChild.Id.Replace("ListingURE_listColumn_", string.Empty).Replace("_0_0", string.Empty)
                    });
                }
                catch { }
            }

            return reports.FirstOrDefault(x => x.Title == reportName);
        }

        private HtmlWindow GetWorkspaceBodyFrame()
        {
            var frame = browser.Document.Window.Frames["headerPlusFrame"];

            frame = frame.Frames.Cast<HtmlWindow>().FirstOrDefault(x => x.Name == "dataFrame");
            if (frame == null) return null;

            frame = frame.Frames.Cast<HtmlWindow>().FirstOrDefault(x => x.Name == "workspaceFrame");
            if (frame == null) return null;

            return frame.Frames.Cast<HtmlWindow>().FirstOrDefault(x => x.Name == "workspaceBodyFrame");
        }

        #region When parameters windows shows

        static DateTime startParametersWindows;

        public delegate void timerPointer();

        private void timerParametersWindow_Elapsed(object sender, ElapsedEventArgs e)
        {
            BeginInvoke(new timerPointer(ClickOkParametersWindow));
        }

        private void ClickOkParametersWindow()
        {
            var buttonId = "theBttnCenterImgpromptsOKButton";
            var location = string.Format("{0}.{1}", JavascriptFrameBody, "frames['webiViewFrame']");
            var javascriptButtonRunQuery = string.Format("{0}.document.getElementById('{1}')", location, buttonId);
            var found = false;

            try
            {
                found = browser.AllElementExist(javascriptButtonRunQuery);
            }
            catch { }

            if (!found && (startParametersWindows - DateTime.Now).TotalSeconds <= 60) return;

            timerParametersWindow.Stop();
            ClickOnElement(buttonId, location, null, null);
        }

        #endregion

        private void button2_Click(object sender, EventArgs e)
        {
            var url = "https://itboprg.nam.nsroot.net/InfoViewApp/listing/main.do?appKind=InfoView?service=%2FInfoViewApp%2Fcommon%2FappService.do?loc=en";
            browser.Navigate(url);
        }

    }

    public class Report
    {
        public HtmlElement ElementClick { get; set; }
        public string Title { get; set; }
        public string Index { get; set; }
    }
}
